<template>
  <div class="cartDetail">
    <div class="content">
        <van-checkbox-group v-model="checked" @change="groupChange">
            <!--store.state.cartList : 状态管理中的购物车列表  -->
          <div v-for="(item,index) in store.state.cartList" :key="index">
            <!-- item', "handleAdd", "handleChange": ListItem.vue中的poprs -->
            <ListItem 
            :item="item"
            :showCheckBox="true" 
            :handleChange="handleChange"/>
          </div>
        </van-checkbox-group>
    </div>

    <!-- 提交订单： -->
    <van-submit-bar
     :price="allPrice"
     button-text="结算"
     @submit="onSubmit"
     class="submit-all"
     buttonColor="#ffc400"
      v-if="store.state.isDelete">
      <van-checkbox v-model="submitChecked" checked-color="#ffc400"
      @click="choseAll">全选</van-checkbox>
    </van-submit-bar>

    <!--点击编辑时：出现的部分  -->
    <div class="buy" v-else>
    <div class="left">
          <van-checkbox v-model="submitChecked" checked-color="#ffc400"
          @click="choseAll">全选</van-checkbox>
     </div>
        <div class="delete" @click="handleDelete">
            删除
        </div>
    </div>

  </div>
</template>

<script>
import { reactive, toRefs,onMounted,computed } from 'vue'
import {useStore} from 'vuex'
import ListItem from '../../../components/ListItem.vue'
import {Toast} from 'vant'
import { useRouter } from 'vue-router'

export default {
    props:['changeShow'],
    components:{ ListItem },
    setup(props){
        const store  = useStore()
        const router = useRouter()

        const data = reactive({
            checked:[],//复选框选中状态
            submitChecked:true //购物车全选：默认选中
        });
        // ListItem.vue中的poprs : 方法
        const handleChange = (value,detail) => {
            // map: 循环遍历
            store.state.cartList.map(item => {
                if(item.id === detail.name){
                    item.num = value//value : handleChange里面的值
                }
            })
        };
        //跳转购物车时，复选框默认全选的状态
        const init = ()=>{
            data.checked = store.state.cartList.map(item=>item.id)
        }
        // 调用方法：
        onMounted(()=>{
            init()
        });
        // onSubmit: 提交订单的按钮
        const onSubmit = () => {
            if(data.checked.length){
                store.commit('pay',updateData())//状态管理中的：pay
                router.push({
                    path: '/createorder',
                    query:{
                        list: data.checked
                    }
                })//路由跳转
            }else{
                Toast.fail("请选择商品")
            }
        }
        //choseAll方法 ： 全选按钮的判断
        const choseAll  = ()=>{
            if(data.checked.length !== store.state.cartList.length){
                init();
            }else{
                data.checked = []
            }
        }
        //groupChange ： 单选按钮的判断
        const groupChange = (result)=>{
            // console.log(result);被选中的有几个
            // 当单选按钮全部选中时，全选按钮为true、否则为false；
            if(result.length === store.state.cartList.length){
                data.submitChecked = true 
            }else{
                data.submitChecked = false
            }
            data.checked = result
        }
        //allPrice : 总价计算
        const allPrice = computed(()=>{
            let countList = updateData()//调用updateData方法
            let sum = 0;
            countList.forEach(item=>{
                sum += item.num * item.price
            })
            return sum * 100
        })
       
          //获取单选的item.id,如果单选里面包含这个item.id
          // filter : 过滤器；includes：是否包含；
          // 如果type === 'delete'：那么就取反，否则就直接是item.id
        const updateData = (type) =>{
            return store.state.cartList.filter(item => {
                return type === 'delete' ? !data.checked.includes(item.id) 
                : data.checked.includes(item.id)
            })
        }
       
        //handleDelete ： 删除
        const handleDelete = ()=>{
            //部分删除 : 判断data的checked是否有值
            if(data.checked.length){
                // 调用状态管理中的 delete
                store.commit('delete',updateData("delete"))
                data.checked = []
                //购物车没有数据时：显示Empty
                if(!store.state.cartList.length){
                    props.changeShow();
                    store.commit("edit","delete")
                }
            }else{
                Toast.fail("请选择要删除的商品")
            }

            //全部删除
        }


        return {
            ...toRefs(data), store, handleChange, init, 
            onSubmit, choseAll, groupChange, allPrice, handleDelete, updateData
        }
    }
}
</script>

<style lang="less" scoped>
.cartDetail {
    font-size: 14px;
    flex: 1;
    position: relative;
    overflow-y: auto;
    padding: 20px 20px 55px;
    .submit-all {
      position: fixed;
      bottom: 46px;
    }

    .buy {
      position: fixed;
      bottom: 48px;
      right: 0;
      display: flex;
      justify-content: space-between;
      width: 100%;
      background-color: #fff;
      border-radius: 10px;
      height: 50px;
      align-items: center;
      padding: 0 16px;
      box-sizing: border-box;
      .left {
        display: flex;
        align-items: center;
      }
      .delete {
        color: #fff;
        background-color: #ffc400;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 600;
        width: 110px;
        height: 40px;
        text-align: center;
        line-height: 40px;
      }
    }

    .content {
      padding: 10px;
      background-color: #fff;
      border-radius: 10px;
    }
  }
</style>